package web.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import web.common.CutPageBean;
import web.common.Result;
import web.entity.*;
import web.mapper.SystemManageMapper;

import web.service.SystemManageService;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SystemManageServiceImpl implements SystemManageService {

    @Autowired
    private SystemManageMapper systemManageMapper;

    @Override
    public boolean changeLoginVerificationCodeStatus(String status) {
        return systemManageMapper.changeLoginVerificationCodeStatus(status);
    }

    @Override
    public CutPageBean<HashMap<String, Object>> grouplist(RoleVo vo) {
//        List<HashMap<String, Object>> res = systemManageMapper.grouplist(vo);
        List<HashMap<String, Object>> res = systemManageMapper.grouplist(vo);
        Integer totalCount = systemManageMapper.totalCount(vo);
        CutPageBean<HashMap<String, Object>> cutPage = new CutPageBean<>();
        cutPage.initCutPage(totalCount, vo.getPageSize(), res);
        return cutPage;
    }

    /**
     * 修改组禁用状态
     * @param id 组id
     * @param status 状态
     * @return String
     */
    @Override
    public Result changeStatus(String id, String status){
        Integer res = systemManageMapper.statusChange(id,status);
        if(res ==0){
            return Result.fail("操作失败");
        }else{
            return Result.succ("");
        }
    }

    //region 列表样式选择成员
    /**
     * 获取弹出层用户列表
     * @param vo 用户
     * @param role 组id
     * @param type tab类型
     * @return json
     */
    @Override
    public CutPageBean<HashMap<String, Object>> userList(UserVo vo, String role, String type) {
        List<HashMap<String, Object>> res;
        Integer totalCount ;
        if(type == null || type.equals("所有人员") || type.equals("")){
            List<HashMap<String, Object>> userlistByRole = systemManageMapper.userListByRole(vo, role);
            res = systemManageMapper.userList(vo);
            if(res.size() != 0){
                for(HashMap<String, Object> allPer:res)
                {
                    String idNow = allPer.get("id").toString();
                    if(userlistByRole.size() != 0)
                    {
                        for(HashMap<String, Object> rolePer:userlistByRole)
                        {
                            String idByRole = rolePer.get("id").toString();
                            if(idNow.equals(idByRole))
                            {
                                allPer.put("role_id",role);
                                break;
                            }
                            else {
                                allPer.put("role_id","");
                            }
                        }
                    }
                    else{
                        allPer.put("role_id","");
                    }
                }
            }

            totalCount = systemManageMapper.userCount(vo);
        }
        else{
            res = systemManageMapper.userListByRole(vo, role);
            totalCount = systemManageMapper.userCountByRole(vo, role);
        }

        CutPageBean<HashMap<String, Object>> cutPage = new CutPageBean<>();
        cutPage.initCutPage(totalCount, vo.getPageSize(), res);
        return cutPage;
    }

    /**
     * 弹出框移除已选成员
     * @param user_id 用户id
     * @param role_id 组id
     * @return String
     */
    @Override
    public Result moveMember(String user_id, String role_id){
        Integer res = systemManageMapper.moveMember(user_id,role_id);
        if(res ==0){
            return Result.fail("操作失败");
        }else{
            return Result.succ("");
        }
    }

    /**
     * 弹出框添加成员
     * @param user_id 用户id
     * @param role_id 权限组id
     * @param type 操作类型
     * @return String
     */
    @Override
    public Result addMember(String user_id, String role_id, String type){
        Integer res = 0;
        if(type.equals("add")){
            res = systemManageMapper.addMember(user_id,role_id);
        }
        else if(type.equals("del")){
            res = systemManageMapper.moveMember(user_id,role_id);
        }
        if(res ==0){
            return Result.fail("操作失败");
        }else{
            return Result.succ("");
        }
    }
    //endregion

    //region 上下框样式选择成员
    /**
     * 获取弹出层用户列表 另一种样式
     * @param vo 用户
     * @param role 组id
     * @param type tab类型
     * @return List
     */
    @Override
    public List<CutPageBean<HashMap<String, Object>>> userListNew(UserVo vo, String role, String type) {
        List<CutPageBean<HashMap<String, Object>>> res = new ArrayList<>();

        /*获取已选成员*/
        List<HashMap<String, Object>> userlistByRole = systemManageMapper.userListByRoleNew(vo, role);
        Integer totalCount = systemManageMapper.userCountByRole(vo, role);
        CutPageBean<HashMap<String, Object>> cutPage = new CutPageBean<>();
        cutPage.initCutPage(totalCount, vo.getPageSize(), userlistByRole);
        res.add(cutPage);

        /*获取所有人员*/
        totalCount = systemManageMapper.userCount(vo);
        List<HashMap<String, Object>> allUser = systemManageMapper.userListNew(vo);
        if(res.size() != 0){
            for(HashMap<String, Object> allPer:allUser)
            {
                String idNow = allPer.get("id").toString();
                if(userlistByRole.size() != 0)
                {
                    for(HashMap<String, Object> rolePer:userlistByRole)
                    {
                        String idByRole = rolePer.get("id").toString();
                        if(idNow.equals(idByRole))
                        {
                            allPer.put("role_id",role);
                            break;
                        }
                        else {
                            allPer.put("role_id","");
                        }
                    }
                }
                else{
                    allPer.put("role_id","");
                }
            }
        }

        CutPageBean<HashMap<String, Object>> cutPageTwo = new CutPageBean<>();
        cutPageTwo.initCutPage(totalCount, vo.getPageSize(), allUser);
        res.add(cutPageTwo);

        return res;
    }
    //endregion

    //region 穿梭框选择成员
    /**
     * 获取弹出层用户列表 第三种样式
     * @param vo 用户
     * @param role 组id
     * @param type tab类型
     * @return List
     */
    @Override
    public List<HashMap<String,String>> userListTwo(UserVo vo, String role, String type){
        List<HashMap<String,String>> res = new ArrayList<>();
        List<UserVo> leftValue = systemManageMapper.userListTwo(vo,role);

        for (UserVo perEntity :leftValue) {
            HashMap<String,String> persons = new HashMap<>();
            persons.put("value",perEntity.getId().toString());
            persons.put("title",perEntity.getUser_name());
            res.add(persons);
        }
        return res;
    }

    /**
     * 获取成员
     * @param role 权限组id
     * @return ArrayList
     */
    public ArrayList<String> userListTwoChoose(String role){
        List<UserVo> rightValue = systemManageMapper.userListTwoChoose(role);
        ArrayList<String> res = new ArrayList<>();
        for(UserVo vo:rightValue){
            res.add(vo.getId().toString());
        }

        return res;
    }

    /**
     * 保存成员信息
     * @param checkedDatas 成员信息
     * @return String
     */
    public Result saveCheckedDatasTwo(Object checkedDatas, String role){
        Integer res;
        systemManageMapper.delMemByRole(role);
        List<Object> entity = (List<Object>) checkedDatas;
        int insertNum = 0;
        for (Object o : entity) {
            LinkedHashMap dataNow = (LinkedHashMap) o;
            res = systemManageMapper.saveCheckedDatasTwo(dataNow.get("value").toString(), role);

            if (res != 0) {
                insertNum = insertNum + 1;
            }
        }
        if(insertNum != entity.size()){
            return Result.fail("操作失败");
        }else{
            return Result.succ("");
        }
    }
    //endregion

    /**
     * 新建或编辑权限组相关信息
     * @param dataObj 权限组信息
     * @return String
     */
    @Override
    public Result addOrEditAuthority(Object dataObj){
        Date d = new Date();
        SimpleDateFormat timeNow= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeStr =timeNow .format(d);

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        Security_UserDetail user = (Security_UserDetail) authentication.getPrincipal();
        UserDo admin = user.getUserDo();
        String userNow = admin.getAccount();

        Map entity = (Map)dataObj;
        String name = entity.get("name").toString();
        String remark = entity.get("remark").toString();
        String roleId = entity.get("idNow").toString();
        String changeRole = entity.get("changeRole").toString();
        Object dataAuthority = entity.get("dataAuthority");

        Integer res = 0; //操作权限组结果
        if(entity.get("type").toString().equals("add")){
            res = systemManageMapper.addAuthority(name,remark,timeStr,userNow);
        }
        else{
            res = systemManageMapper.editAuthority(name,remark,roleId,timeStr,userNow);
        }

        String newRoleId = entity.get("idNow").toString();
        Integer delRes= 0;
        if(changeRole.equals("yes")){
            if(entity.get("type").toString().equals("add")){
                //判重
                Integer accountExist = systemManageMapper.isAccountExist(entity.get("name").toString());
                if (accountExist != 0) {
                    return Result.fail("权限组已存在");
                }
                else{
                    List<RoleVo> roleData = systemManageMapper.getNewestOne();
                    newRoleId = roleData.get(0).getId().toString();
                }
            }else{
                delRes = systemManageMapper.deleteOldPermission(entity.get("idNow").toString());
                /*if(delRes == 0){
                    res = -1;
                }*/
            }

            if(res != 0 && dataAuthority != null && dataAuthority != ""){
                String insertStr = "";
                List<Object> checkDatas = (List<Object>) dataAuthority;
                for(Integer m = 0; m < checkDatas.size(); m++){
                    LinkedHashMap menuOwn = (LinkedHashMap)checkDatas.get(m);
                    if(menuOwn.get("id").equals(0)){
                        List<Object> secondData = (List<Object>) menuOwn.get("children");
                        for(Integer n = 0; n < secondData.size(); n++){
                            LinkedHashMap menuTwo = (LinkedHashMap)secondData.get(n);
                            res = systemManageMapper.insertNewPermission(newRoleId,menuTwo.get("id").toString());
                        }
                    }
                }
            }
        }

        if(res ==0){
            return Result.fail("操作失败");
        }else{
            return Result.succ("");
        }
    }

    /**
     * 获取权限树
     * @param role_id 权限组id
     * @return List
     */
    @Override
    public List<AuthorityTree> getMenuTree(String role_id){
        List<AuthorityTree> res = new ArrayList<>();
        List<MenuEntity> allMenu = systemManageMapper.getMenuTree(); //所有菜单
        List<RoleMenu> menuByRole = systemManageMapper.getMenuByRole(role_id); //该权限组已有权限

        HashSet<String> parentNames = new HashSet<>();
        for (MenuEntity menuEntity :allMenu) {
            parentNames.add(menuEntity.getParent());
        }

        for(String parentName :parentNames){
            AuthorityTree treeFather = new AuthorityTree();
            if(parentName != null &&  !parentName.equals("")){
                treeFather.title = parentName;
                treeFather.id = 0;
                treeFather.spread = true;

                List<AuthorityTree> childrens = new ArrayList<>();
                for(MenuEntity getchild :allMenu){
                    if (parentName.equals(getchild.getParent())){
                        AuthorityTree treeChild = new AuthorityTree();
                        treeChild.title = getchild.getMenuName();
                        treeChild.id = getchild.getId();
                        for(RoleMenu roleMenu:menuByRole){
                            treeChild.checked = false;
                            if(getchild.getId().toString().equals(roleMenu.getMenu_id())) {
                                treeChild.checked = true;
                                break;
                            }
                        }
                        childrens.add(treeChild);
                    }
                }
                treeFather.children=childrens;
                res.add(treeFather);
            }
        }

        return res;
    }

    /**
     * 删除权限组
     * @param role_id 权限组id
     * @return Stirng
     */
    @Override
    public Result deleteAuthority(String role_id){
        Integer res = systemManageMapper.deleteAuthority(role_id);
        if(res ==0){
            return Result.fail("操作失败");
        }else{
            return Result.succ("");
        }
    }
}
